package com.shioirikukuri.service.impl;

import com.shioirikukuri.entity.User;
import com.shioirikukuri.mapper.CustomerMapper;
import com.shioirikukuri.service.ICustomerService;
import com.shioirikukuri.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class CustomerServiceImpl implements ICustomerService {

	@Autowired
	private CustomerMapper customerMapper;

	/*

		登录业务逻辑：
		1. 根据手机号查询用户
		2. 验证密码（假设盐值为 "salt"）
		3. 返回用户信息
	 */
	@Override
	public User login(String phoneNumber, String password) {
		// 1. 根据手机号查询用户
		User user = customerMapper.findByPhoneNumber(phoneNumber);
		if (user == null) {
			throw new RuntimeException("用户不存在");
		}

		// 2. 验证密码（假设盐值为 "salt"）
		String encryptedPassword = MD5Util.encode(password, "salt");
		if (!encryptedPassword.equals(user.getPassword())) {
			throw new RuntimeException("密码错误");
		}

		// 3. 返回用户信息
		return user;
	}

	@Override
	public Optional<User> findConsumerByPhoneNumber(String phoneNumber) {
		User user = customerMapper.findConsumerByPhoneNumber(phoneNumber);
		if (user == null) {
			return Optional.empty();
		}
		if (!user.getRole().equals(User.CONSUMER)) {
			return Optional.empty();
		}
		return Optional.of(user);
	}
}